package com.gitee.loyo.controller;

import com.gitee.loyo.*;
import com.gitee.loyo.page.AuthPage;
import com.gitee.loyo.utils.HttpUtils;
import io.vertx.core.Future;
import io.vertx.core.Promise;
import io.vertx.core.http.HttpServerRequest;
import io.vertx.core.json.JsonObject;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;

import javax.ws.rs.GET;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import java.io.StringWriter;

public class AuthController {

    @GET
    @Path("/auth")
    public void getAuth(HttpServerRequest request, Promise<Void> promise){
        AuthPage authPage = new AuthPage();
        authPage.basicAuthEnabled = BridgeConfig.INSTANCE.basicAuthEnabled;
        authPage.username = BridgeConfig.INSTANCE.basicAuthUsername;

        Template tmpl = Global.VELOCITY_ENGINE.getTemplate("vm/auth.vm");
        VelocityContext ctx = new VelocityContext();
        ctx.put("page", authPage);
        StringWriter output = new StringWriter();
        tmpl.merge(ctx, output);
        Pages.renderPage(request.response(), output.toString());
        promise.complete();
    }

    @PUT
    @Path("/auth")
    public void updateAuth(HttpServerRequest request, Promise<Void> promise){
        Future.<String>future(p ->
            HttpUtils.getBodyAsString(request, p)
        ).map(JsonObject::new).compose(json -> {
            Boolean basicAuthEnabled = json.getBoolean("basicAuthEnabled", false);
            String username = json.getString("username", "");
            String password = json.getString("password", "");
            if(basicAuthEnabled && (username.isEmpty() || password.isEmpty())){
                return Future.failedFuture("illegal parameter");
            }
            return Auth.save(basicAuthEnabled, username, password);
        }).onComplete(ar -> {
            if(ar.failed()){
                ar.cause().printStackTrace();
                request.response().setStatusCode(400).end(ar.cause().getMessage());
            }else{
                request.response().setStatusCode(200).end();
            }
            promise.complete();
        });
    }
}
